package com.young.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DLXQueueConfig {
    //=====================定义一个会将符合条件的队列转发到死信队列的队列 正常的队列在一定条件下会转发到死信队列==================
    /**
     * 定义一个允许转发到私信队列的队列
     * @return
     */
    @Bean
    public Queue allowDlxQueue(){
        Map<String, Object> map = new HashMap<>();
        // 通过x-dead-letter-exchange将队列声明成包含死信队列的队列，my_dlx_exchange为死信交换机名称
        map.put("x-dead-letter-exchange", "my_dlx_exchange");
        // 队列中的消息未被消费则30秒后过期，过期后将会被转发到死信队列
        map.put("x-message-ttl", 30000);
        return new Queue("allow_dlx_queue", true, false, false, map);
    }

    /**
     * 定义一个交换机，该交换机绑定正常队列
     * @return
     */
    @Bean
    public DirectExchange allowDlxExchange() {
        return new DirectExchange("allow_dlx_change", true, false);
    }

    /**
     * 将正常队列与正常的交换机进行绑定
     * @return
     */
    @Bean
    public Binding bindingAllowDlx() {
        return BindingBuilder.bind(allowDlxQueue()).to(allowDlxExchange()).with("dlx_routingkey");
    }


    //=======================================死信队列=========================================================
    /**
     * 定义死信队列
     * @return
     */
    @Bean
    public Queue DLXQueue(){
        return new Queue("my_dlx_queue", true, false, false, null);
    }

    /**
     * 定义死信交换机
     * @return
     */
    @Bean
    public DirectExchange DlxExchange() {
        return new DirectExchange("my_dlx_exchange", true, false);
    }

    /**
     * 将死信队列与死信交换机进行绑定
     * 路由键需要和上面正常队列绑定的路邮件相同，才会进行转发，否则不会转发到死信队列
     * @return
     */
    @Bean
    public Binding bindingDLX() {
        return BindingBuilder.bind(DLXQueue()).to(DlxExchange()).with("dlx_routingkey");
    }
}
